package ru.amse.vlassiev.reader;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.*;

import java.util.Map;

public class UDPReader implements IReader {

	private Queue<byte[]> myMessage;
	private int myPort;
	private IListener myListener;

	public UDPReader(int port) {
		myMessage = new LinkedList<byte[]>();
		myPort = port;
		new Thread(new MessageGetter()).start();
	}

	public void addListener(IListener listener) {
		myListener = listener;
	}

	public Map<String, String> getNextMessage() {
		synchronized (myMessage) {
			return createData(new String(myMessage.poll()));
		}
	}

	public void start() {
		new Thread(new ReaderAction()).start();
	}


	
	private class MessageGetter implements Runnable {
		public void run() {
			try {
				DatagramSocket socket = new DatagramSocket(myPort);
				while (true) {
					byte[] syslogMessage = new byte[1024];
					DatagramPacket packet = new DatagramPacket(syslogMessage, 1024);
					socket.receive(packet);
					synchronized (myMessage) {
						myMessage.add(packet.getData());
					}
				}
			} catch (IOException e) {
			}
		}
	}
	
	private Map<String, String> createData(String message) {
		Map<String, String> result = new HashMap<String, String>();
		StringTokenizer tokenizer = new StringTokenizer(message, " ", false);
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			if (token.indexOf('=') != -1) {
				String[] keyValue = token.split("=");
				result.put(keyValue[0], keyValue[1]);
			}
		}
		String PRI = message.substring(message.indexOf('<') + 1, message.indexOf('>'));
		result.put("PRI", PRI);
		String timestamp = message.substring(message.indexOf('[') + 1, message.indexOf(']'));
		result.put("timestamp", timestamp);
		return result;
	}

	private class ReaderAction implements Runnable {
		public void run() {
			while (true) {
				if (!myMessage.isEmpty()) {
					myListener.newMessage(getNextMessage());
				}
			}
		}
	}
		

}

	
